package com.demo.web;

import com.demo.common.Constants;
import com.demo.common.OrderConstants;
import com.demo.common.PrintContract;
import com.demo.dto.BaseResult;
import com.demo.dto.ListResult;
import com.demo.dto.Pagination;
import com.demo.entity.*;
import com.demo.service.*;
import com.demo.entity.*;
import com.demo.service.*;
import com.demo.utils.PdfHelper;
import com.demo.utils.PdfUtils;
import com.demo.vo.ContractVO;
import com.demo.vo.GoodsVo;
import com.demo.vo.OrderVo;
import com.demo.vo.UserVo;
import com.lowagie.text.DocumentException;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/admin/order")
public class OrderController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IOrderService depService;
    @Autowired
    private IClienteleService clienteleService;
    @Autowired
    private IOfferService offerService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ISaleCommissionService saleCommissionService;
    @Autowired
    private IOrderPaperService orderPaperService;
    @Autowired
    private IOrderOperateLogService orderOperateLogService;


    /**
     * 创建
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public BaseResult<Integer> create(Order arg) {
        int service_res = depService.insertSelective(arg);
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public BaseResult<Order> get(Order arg) {
        Order service_res = depService.selectByPrimaryKey(arg.getId());
        return new BaseResult<Order>(true, service_res);
    }

    /**
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public BaseResult<Object> delete(Order arg) {
//      int service_res = depService.deleteByPrimaryKey(arg.getId());
        BaseResult<Object> res = new BaseResult(false, "", 403);
        return res;
    }

    /**
     * 合同打印
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/print", method = RequestMethod.GET)
    public BaseResult<Object> print(Order arg) {
        ContractVO cv = new ContractVO();
        Order order = depService.selectByPrimaryKey(arg.getId());
        Offer offer = offerService.selectByPrimaryKey(Integer.valueOf(order.getOfferId()));
//        Offer offer = storeService.selectByPrimaryKey(offerService.get).selectByPrimaryKey(Integer.valueOf(order.getOfferId()));
        Goods goods = goodsService.selectByPrimaryKey(Integer.valueOf(order.getGoodsId()));
        Clientele clientele = clienteleService.selectByPrimaryKey(Integer.valueOf(order.getClienteleId()));
        cv.setBuyer(order.getClienteleName());
        User u = new User();
        u.setId(Integer.valueOf(offer.getCreatorId()));
        User user = userService.selectDepByPrimaryKey(u);
        if (user != null) {
            cv.setTel(user.getComName());
            cv.setFax(user.getDepName());
            cv.setName(user.getName());
        } else {
            cv.setTel("021-60482075/60482076");
            cv.setFax("021-54738871/54738880");
            cv.setName("王文庆");
        }
        cv.setQualityRequire(offer.getQualityRequire());
        cv.setPaymentCondition(order.getPayCondition() != null ? order.getPayCondition() : " ");
        cv.setCompany(order.getClienteleName());
        cv.setGoodName(order.getGoodsName());
        cv.setQuality(offer.getQualitySpec());
        cv.setContactAddress(clientele.getAddress());
        cv.setContactTel(order.getClienteleUserPhone());
        cv.setContractNO(order.getNo());
        cv.setContactFax(clientele.getFax());
        cv.setRepresentative(clientele.getPerson());
        cv.setPriceUnit(offer.getPriceUnit());
        cv.setUnit((offer.getUnit() != null ? offer.getUnit() : goods.getUnit()));
        cv.setCounts(String.valueOf(order.getNumber()));
        cv.setStatus(order.getCheckStatus());
        Date date = order.getDeliveryDay();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
        cv.setDeliveryDate(sdf.format(date));
//        cv.setDeliveryWay(order.getDeliveryType().equals("0") ? "自提" : "免费配送");
        cv.setDeliveryWay(order.getPickUpMethod().equals("0") ? "需方自提" + offer.getDeliverPlace() : "送货至需方仓库");
        cv.setDescription(goods.getDesc());
        cv.setPaymentWay(order.getPayMethod().equals("0") ? "银行电汇" : (order.getPayMethod().equals("1") ? "承兑汇票" : (order.getPayMethod().equals("2") ? "国内信用证" : "")));
        cv.setPaymentDate(new SimpleDateFormat("yyyy-MM-dd").format(order.getPayDate()));
        Integer freeDay = (Integer.valueOf(order.getFreeStoreDay()));
        if (freeDay > 0) {
            freeDay -= 1;
        }
        cv.setFreeDate((order.getFreeStoreType().equals("0") ? new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * freeDay)) : ("交割日起" + order.getFreeStoreDay() + "天")));
//
        cv.setStorePrice("");
        cv.setWrap(offer.getPackSpec());
        cv.setTimePlace(new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " 上海");
        cv.setPrice(String.valueOf(order.getActualPrice()));
        Double d = order.getActualPrice() * order.getNumber();
        cv.setMoney(String.valueOf(d));
        cv.setContractValue(PrintContract.change(d));
        BaseResult<Object> res = new BaseResult(true, cv);
        return res;
    }

    /**
     * 获取订单合同
     *
     * @param order
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getOrderPaper", method = RequestMethod.GET)
    public BaseResult<Object> getOrderPaper(Order order) {
        if (order.getId() == null) {
            return new BaseResult(false, "参数非法");
        }

        OrderPaper op = orderPaperService.selectByOrderId(String.valueOf(order.getId()));
        Order order_ = depService.selectByPrimaryKey(order.getId());
        Map<Object, Object> o = new HashMap<Object, Object>();
        if (op != null) {
            if (op.getPaper() != null) {
                o.put("body", new String(op.getPaper()));
            } else {
                o.put("body", "");
            }

            o.put("type", op.getType());
            o.put("path", op.getPath());
            o.put("single", op.getSingle());
            o.put("checkStatus", order_.getCheckStatus());
            o.put("couple", op.getCouple());
        }

        return new BaseResult(true, o);
    }

    @RequestMapping(value = "/{id}-{clientleName}.pdf")
    public OutputStream toPdf(Order order, String id, String clientName, HttpSession session, HttpServletResponse response) throws DocumentException, TemplateException, IOException {
        OrderPaper op = orderPaperService.selectByOrderId(String.valueOf(order.getId()));
        String path = PdfHelper.getPath();
        ClassPathResource resource = new ClassPathResource("tpl.ftl");
        Map<Object, Object> o = new HashMap<Object, Object>();
        o.put("body", new String(op.getPaper()));
        String path_ = resource.getURL().toString().replace("tpl.ftl", "");
        return PdfUtils.generateToServletOutputStream(path_.replace("file:" + (path_.indexOf("usr/") > -1 ? "" : "/"), ""), "tpl.ftl",
                resource.getURL().toString().replace("tpl.ftl", ""), o, response);
    }

    @ResponseBody
    @RequestMapping(value = "/save-paper", method = RequestMethod.POST)
    public BaseResult savePaper(OrderPaper op, HttpSession session) {
        User user = (User) session.getAttribute(Constants.USER);
        if (user
                == null) {
            return new BaseResult(false, "未登录!", 401);
        }
        if (op.getOrderId() == null) {
            return new BaseResult(false, "参数不完整!", 403);
        }


        OrderPaper op_res = orderPaperService.selectByOrderId(op.getOrderId());


        int res = 0;
        if (op_res == null) {
            op.setUserId(String.valueOf(user.getId()));
            res = orderPaperService.insertSelective(op);
        } else {
            op_res.setUserId(String.valueOf(user.getId()));
            op_res.setPaper(op.getPaper());
            op_res.setPath(op.getPath());
            op_res.setType(op.getType());
            op_res.setSingle(op.getSingle());
            op_res.setCouple(op.getCouple());
            res = orderPaperService.updateByPrimaryKeySelective(op_res);
            return new BaseResult(true, res);
        }
        if (res > 0) {
            String type = "";
            if (op.getPaper() != null) {
                type = OrderConstants.ORDER_SAVE_PAPER;
            } else if (op.getPath() != null) {
                type = OrderConstants.ORDER_UPLOAD_PAPER;
            } else if (op.getSingle() != null) {
                type = OrderConstants.ORDER_UPLOAD_SINGLE_PAPER;
            } else if (op.getCouple() != null) {
                type = OrderConstants.ORDER_UPLOAD_COUPLE_PAPER;
            }
            orderOperateLogService.insertLog(String.valueOf(user.getId()), type, op.getOrderId());
        }
        return new BaseResult(true, res);
    }


    /**
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public BaseResult<Integer> update(Order arg) {
        arg.setCheckStatus(null);//禁止通过update审核
        arg.setActualPrice(null); //禁止通过update收款
        arg.setPayStatus(null); //禁止通过update收款
        int service_res = depService.updateByPrimaryKeySelective(arg);
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    /**
     * 收款
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/payed", method = RequestMethod.POST)
    public BaseResult<Object> payed(Order arg, HttpSession session) {
        Order order = new Order();
        BaseResult<Object> res = null;
        User user = (User) session.getAttribute(Constants.USER);
        if (user == null) {
            return new BaseResult(false, "未登录!", 401);
        }
        order.setPayStatus("1");
        Order service_res = depService.selectByPrimaryKey(arg.getId());
        if (service_res != null) {
            if (!"0".equals(service_res.getStatus())) {
                return new BaseResult(false, "订单状态不在执行中，不能再次收款!", 403);
            }
            if (service_res.getPayStatus().equals("1")) {
                return new BaseResult(false, "订单已经收款，不能再次收款!", 403);
            }
            order.setActualTotal(service_res.getActualTotal());
            order.setId(arg.getId());
            order.setOfferId(String.valueOf(user.getId())); //操作员
            Integer pay_res = (Integer) depService.payed(order);
            if (pay_res > 0) {
                orderOperateLogService.insertLog(String.valueOf(user.getId()), OrderConstants.ORDER_RECEIVE_MONEY, arg.getId().toString());
            }
            res = new BaseResult(true, pay_res);
        } else {
            res = new BaseResult(false, "订单不存在!", 403);
        }
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/updatePrice", method = RequestMethod.POST)
    public BaseResult<Object> updatePrice(Order arg, HttpSession session) {
        User user = (User) session.getAttribute(Constants.USER);
        if (user == null) {
            return new BaseResult(false, "未登录!", 401);
        }
        Order order = depService.selectByPrimaryKey(arg.getId());
        Object service_res = depService.updatePrice(arg);
        if (service_res instanceof String) {
            return new BaseResult(false, service_res.toString(), 403);
        } else if (service_res instanceof Integer) {
            int service_ = (int) service_res;
            if (service_ > 0) { //
                orderOperateLogService.insertLog(String.valueOf(user.getId()), OrderConstants.ORDER_UPDATE_PRICE, arg.getId().toString(), order.getActualPrice() + "->" + arg.getActualPrice());
            }
        }
        BaseResult<Object> res = new BaseResult(true, service_res);
        return res;
    }

    /**
     * 强制终止订单执行
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/forceEnd", method = RequestMethod.POST)
    public BaseResult<Object> forceEnd(Order arg, HttpSession session) {
        User user = (User) session.getAttribute(Constants.USER);
        if (user == null) {
            return new BaseResult(false, "未登录!", 401);
        }
        Order order = new Order();
        order.setId(arg.getId());
        order.setStatus("2");
        Object service_res = depService.forceEnd(order);
        if (service_res instanceof String) {
            return new BaseResult(false, service_res.toString(), 403);
        } else if (service_res instanceof Integer) {
            int service_ = (int) service_res;
            if (service_ > 0) { //
                orderOperateLogService.insertLog(String.valueOf(user.getId()), OrderConstants.ORDER_FORCE_END, arg.getId().toString());
            }
        }
        BaseResult<Object> res = new BaseResult(true, service_res);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/endOrder", method = RequestMethod.POST)
    public BaseResult<Object> endOrder(Order arg, HttpSession session) {
        User user = (User) session.getAttribute(Constants.USER);
        if (user == null) {
            return new BaseResult(false, "未登录!", 401);
        }
        Order order = new Order();
        order.setId(arg.getId());
        order.setStatus("1");
        Object service_res = depService.forceEnd(order);
        if (service_res instanceof String) {
            return new BaseResult(false, service_res.toString(), 403);
        } else if (service_res instanceof Integer) {
            int service_ = (int) service_res;
            if (service_ > 0) { //
                orderOperateLogService.insertLog(String.valueOf(user.getId()), OrderConstants.ORDER_END, arg.getId().toString());
            }
        }
        BaseResult<Object> res = new BaseResult(true, service_res);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/checkStatus", method = RequestMethod.POST)
    public BaseResult<Object> checkStatus(Order arg, HttpSession session) {
        User user = (User) session.getAttribute(Constants.USER);
        if (user == null) {
            return new BaseResult(false, "未登录!", 401);
        }
        arg.setChecker(String.valueOf(user.getId()));
        arg.setCheckTime(new Date());

        Object service_res = depService.checkOrder(arg);
        if (service_res instanceof String) {
            return new BaseResult<Object>(false, service_res.toString(), 403);
        } else if (service_res instanceof Integer) {
            int service_ = (int) service_res;
            if (service_ > 0) { //
                orderOperateLogService.insertLog(String.valueOf(user.getId()), OrderConstants.ORDER_CHECK, arg.getId().toString(), "1".equals(arg.getCheckStatus()) ? "审核通过" : "审核拒绝");
            }
        }
        BaseResult<Object> res = new BaseResult(true, service_res);
        return res;
    }

    /***
     * 分页查询
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public ListResult query(OrderVo arg, HttpSession session) {

        UserVo user = (UserVo) session.getAttribute(Constants.USER);
        if (user == null) {
            return new ListResult(false, "未登录!", 401);
        }
        Boolean isManger = false;
        for (Role role : user.getRoles()) {
            if (String.valueOf(role.getId()).equals(Constants.SUPER_MANAGER_ROLE_ID)) { /// 超级管理员账户判断
                isManger = true;
            }
        }
        if (!isManger) { //运营账户判断判断
            GoodsVo goods = new GoodsVo();
            List<Goods> list = goodsService.queryGoodsCategory(goods);
            List<String> lstr = new ArrayList<String>();
            for (Goods item : list) {
                if (("," + item.getOperatorId() + ",").indexOf("," + user.getId() + ",") > -1) {
                    lstr.add(String.valueOf(item.getId()));
                }
            }
            if (lstr.size() > 0) {
                arg.setList(lstr);
            }
        }
        if (!isManger && (null == arg.getList())) {
            return new ListResult(false, "非运营或超级管理员角色账号，无权访问!", 403);
        }
        List<OrderVo> list_order = depService.queryByPage(arg);
        int total = depService.queryCount(arg);
        arg.getPage();
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list_order);
        res.setPage(page);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/queryByClienteleIdAndOfferId", method = RequestMethod.GET)
    public ListResult queryByClienteleIdAndOfferId(OrderVo arg) {
        List<OrderVo> list = depService.queryOrdersByOfferIdAndClienteleId(arg);
        int total = depService.queryOrdersCountByOfferIdAndClienteleId(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }


    @ResponseBody
    @RequestMapping(value = "/queryMyOrder", method = RequestMethod.GET)
    public ListResult<Object> queryMyOrder(OrderVo arg, HttpSession session) {

        User user = (User) session.getAttribute(Constants.USER);
        ListResult<Object> res;
        if (user == null) {
            res = new ListResult(false, "请登录!", 401);
            return res;
        }
        List<OrderVo> list = depService.queryMyOrdersByPage(arg);
        int total = depService.queryMyOrderCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }
}
